package com.vortex.cloud.zhsw.xinyang.util;

import org.springframework.context.support.DefaultMessageSourceResolvable;
import org.springframework.validation.BindingResult;

import java.math.BigDecimal;
import java.util.Set;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

/**
 * 消息验证工具类
 *
 * @author zhouzheqiang@vortexinfo.cn
 */
public class ValidationUtil {

    private static final String TWO_SIZE0 = "(^[0-9](\\d+)?(\\.\\d{1,5})?$)|(^\\d\\.\\d{1,5}$)";
    /**
     * 手机号正则表达式
     */
    private static final String PHONE_REGEX = "^(?:(?:\\+|00)86)?1[3-9]\\d{9}$";
    /**
     * 社会统一信用代码正则表达式
     */
    private static final String USCC_REGEX = "^[0-9A-HJ-NPQRTUWXY]{2}\\d{6}[0-9A-HJ-NPQRTUWXY]{10}$";
    /**
     * 登录密码正则表达式
     */
    private static final String PASSWORD_REGEX = "^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z~!@#$%^&*]{8,16}$";

    public static final int TWO = 2;

    /**
     * 组装验证消息
     *
     * @param bindingResult validator验证结果
     * @return 处理后的消息
     */
    public static String validateMsg(BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            Set<String> errorMsgs = bindingResult.getAllErrors()
                    .stream()
                    .map(DefaultMessageSourceResolvable::getDefaultMessage)
                    .collect(Collectors.toSet());
            return String.join(",", errorMsgs);
        }
        return null;
    }

    /**
     * 判断是否为>=0的两位小数，是则返回true
     */
    public static boolean isTwoSize0(String num) {
        return Pattern.matches(TWO_SIZE0, num);
    }

    /**
     * 校验手机号
     *
     * @param phone
     * @return
     */
    public static Boolean checkPhone(String phone) {
        return Pattern.matches(PHONE_REGEX, phone);
    }

    /**
     * 校验社会统一信息代码
     *
     * @param uscc
     * @return
     */
    public static Boolean checkUscc(String uscc) {
        return Pattern.matches(USCC_REGEX, uscc);
    }

    /**
     * 校验密码 密码为数字字母组合并且不小于8位
     *
     * @param password 密码
     */
    public static Boolean checkPassword(String password) {
        return Pattern.matches(PASSWORD_REGEX, password);
    }

    /**
     * 校验是否满足最多几位小数
     *
     * @param bigdecimal 数
     * @param flagScale 最多小数位
     */
    public static Boolean checkScale(BigDecimal bigdecimal, int flagScale) {
        int scale = bigdecimal.stripTrailingZeros().scale();
        return Math.max(scale, 0) <= flagScale;
    }
}
